package com.yupi.springbootinit.statemachine.rule;

import com.yupi.springbootinit.statemachine.core.Event;
import com.yupi.springbootinit.statemachine.core.State;
import com.yupi.springbootinit.statemachine.core.StateContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务规则引擎
 * 用于验证状态转换的业务规则和条件
 */
@Slf4j
@Component
public class RuleEngine {
    
    /**
     * 规则存储：状态转换 -> 规则列表
     */
    private final Map<String, List<BusinessRule>> ruleRegistry = new ConcurrentHashMap<>();
    
    /**
     * 注册业务规则
     */
    public void registerRule(String entityType, State fromState, State toState, BusinessRule rule) {
        String key = buildRuleKey(entityType, fromState, toState);
        ruleRegistry.computeIfAbsent(key, k -> new ArrayList<>()).add(rule);
        log.info("注册业务规则: {} -> {}", key, rule.getRuleName());
    }
    
    /**
     * 验证状态转换是否符合业务规则
     */
    public RuleValidationResult validateTransition(StateContext context) {
        String key = buildRuleKey(context.getEntityType(), context.getCurrentState(), context.getTargetState());
        List<BusinessRule> rules = ruleRegistry.get(key);
        
        if (rules == null || rules.isEmpty()) {
            log.debug("未找到业务规则: {}", key);
            return RuleValidationResult.success();
        }
        
        log.debug("开始验证业务规则: {}, 规则数量: {}", key, rules.size());
        
        for (BusinessRule rule : rules) {
            try {
                RuleValidationResult result = rule.validate(context);
                if (!result.isValid()) {
                    log.warn("业务规则验证失败: {} - {}", rule.getRuleName(), result.getErrorMessage());
                    return result;
                }
                log.debug("业务规则验证通过: {}", rule.getRuleName());
            } catch (Exception e) {
                log.error("业务规则执行异常: {} - {}", rule.getRuleName(), e.getMessage(), e);
                return RuleValidationResult.failure("规则执行异常: " + e.getMessage());
            }
        }
        
        log.debug("所有业务规则验证通过: {}", key);
        return RuleValidationResult.success();
    }
    
    /**
     * 构建规则键
     */
    private String buildRuleKey(String entityType, State fromState, State toState) {
        return String.format("%s:%s->%s", entityType, fromState.getCode(), toState.getCode());
    }
    
    /**
     * 获取指定状态转换的所有规则
     */
    public List<BusinessRule> getRules(String entityType, State fromState, State toState) {
        String key = buildRuleKey(entityType, fromState, toState);
        return ruleRegistry.getOrDefault(key, new ArrayList<>());
    }
    
    /**
     * 移除业务规则
     */
    public void removeRule(String entityType, State fromState, State toState, String ruleName) {
        String key = buildRuleKey(entityType, fromState, toState);
        List<BusinessRule> rules = ruleRegistry.get(key);
        if (rules != null) {
            rules.removeIf(rule -> rule.getRuleName().equals(ruleName));
            log.info("移除业务规则: {} - {}", key, ruleName);
        }
    }
    
    /**
     * 清空所有规则
     */
    public void clearAllRules() {
        ruleRegistry.clear();
        log.info("清空所有业务规则");
    }
    
    /**
     * 获取规则统计信息
     */
    public Map<String, Integer> getRuleStatistics() {
        Map<String, Integer> stats = new ConcurrentHashMap<>();
        ruleRegistry.forEach((key, rules) -> stats.put(key, rules.size()));
        return stats;
    }
}